package com.imooc.interceptor;

import com.imooc.exception.GraceException;
import com.imooc.grance.result.ResponseStatusEnum;
import com.imooc.utils.IPUtil;
import com.imooc.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 *
 * @auther Levi
 * @Date: 2021/03/13/22:27
 * @Description:
 */
public class PassPortInterceptor  implements HandlerInterceptor {

    public static final String MOBILE_SMSCODE = "mobile:smscode";

    @Autowired
    private RedisOperator redis;

    /**
     * 进入controller之前调用
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 判断key在redis里面存不存在
         * 如果存在返回true:进入controller
         * 如果不存在返回false: 拦截住
         */
        String userIp = IPUtil.getRequestIp(request);
        boolean isExist = redis.keyIsExist(MOBILE_SMSCODE + ":" + userIp);
        if (isExist) {
            //如果throw的话不优雅，所以要写一个自定义异常进行捕获
//            throw new RuntimeException("发生了异常");
           GraceException.display(ResponseStatusEnum.SMS_NEED_WAIT_ERROR);
//            throw new Exception("");
            return false;
        }
        return true;

    }

    /**
     * 进入controller之后,渲染视图之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    /**
     * 进入controller之后,渲染视图之后
     * @param request
     * @param response
     * @param handler
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
